package com.ftwj.demo.global.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @ClassName: CustomLoginFilter
 * @Description: 自定义Shiro过滤器用于权限过滤和Shiro请求日志
 * @author: WangShengLi
 * @date: 2019年7月10日 上午9:58:44
 */
public class CustomLoginFilter extends PathMatchingFilter {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CustomLoginFilter.class);
	 
	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		return super.preHandle(request, response);
	}
	
	@Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        boolean isAuthenticated = subject.isAuthenticated();
        if (!isAuthenticated) {
            HttpServletResponse resp = (HttpServletResponse) response;
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.getWriter().print("权限不足!");
            return false;
        }
        
        HttpServletRequest req=(HttpServletRequest) request;
        LOGGER.info("请求方法:"+req.getMethod());
        LOGGER.info("登录IP地址:"+req.getRemoteAddr());
        return true;
    }

}
